package team.bluepen.supermarket.web.servlet;

import team.bluepen.supermarket.constant.Error;
import team.bluepen.supermarket.constant.Role;
import team.bluepen.supermarket.data.entity.User;
import team.bluepen.supermarket.util.ServletUtil;
import team.bluepen.supermarket.util.StringUtil;
import team.bluepen.supermarket.util.UserChecker;
import team.bluepen.supermarket.web.base.DataServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 用户设置Servlet
 * @author Kai
 */
@WebServlet(name = "UserEditServlet", urlPatterns = "/api/setting-control")
public class UserEditServlet extends DataServlet {
    /**Row ID参数*/
    public static final String USER_ROW_PARAM = "user_row";
    /**用户名参数*/
    public static final String USERNAME_PARAM = "edit_username";
    /**用户密码参数*/
    public static final String PASSWORD_PARAM = "edit_password";
    /**用户角色参数*/
    public static final String ROLE_PARAM = "edit_role";

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
        if (!checkUserRole(req)) {
            resp.sendRedirect(requestSource);
            return;
        }

        String userRow = req.getParameter(USER_ROW_PARAM);
        String newUsername = req.getParameter(USERNAME_PARAM);
        String newPassword = req.getParameter(PASSWORD_PARAM);
        Role newRole = Role.get(req.getParameter(ROLE_PARAM));

        String requestSource = ServletUtil.getRefererUrl(req);

        User editUser = userRepository.query(userRow);

        boolean isUsernameModified = false;
        if (!StringUtil.isEmpty(newUsername)) {
            editUser.setUsername(newUsername);
            isUsernameModified = true;
        }

        if (!StringUtil.isEmpty(newPassword)) {
            editUser.setPassword(newPassword);
        }

        if (newRole != null) {
            editUser.setRole(newRole);
        }

        Error checkState = UserChecker.checkUser(editUser);
        if (!checkState.getState()) {
            resp.sendRedirect(requestSource + "?error=" + checkState.getValue());
            return;
        }

        Error error = userRepository.editUser(editUser, isUsernameModified);
        resp.sendRedirect(requestSource + "?error=" + error.getValue());
    }
}
